// @flow
import React from 'react'
import styles from './ChannelBoard.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import ChannelData from './ChannelData'
import { Tabs } from 'antd'
const TabPane = Tabs.TabPane

type Props = {
  goToCondition: Function,
  channelData: Array<Object>,
  deviceData: Object,
  filterData: Function,
  panelYear: string
}
type States = {
  tabTags: Array<Object>,
  sensorType: string
}
class ChannelBoard extends React.Component {
  props: Props
  state: States
  getVariable: Function
  changeTab: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      tabTags: [],
      sensorType: ''
    }
    this.getVariable = this.getVariable.bind(this)
    this.changeTab = this.changeTab.bind(this)
  }
  changeTab (activeKey: string) {
    this.setState({
      sensorType: activeKey
    })
  }
  componentWillMount () {
    this.getVariable()
  }
  getVariable () {
    const { deviceData } = this.props
    universalFetch(`${__SERVICE_API__}device/devices/${deviceData.id}/channel-ids?type=1`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const sensorItem = json.result.filter((dd) => dd.sensorType === '振动量')
        this.setState({
          tabTags: json.result,
          sensorType: sensorItem.length > 0 ? sensorItem[0].sensorType : json.result[0].sensorType
        })
      })
      .catch((error) => {
        handleFetchError(error)
      })
  }
  render () {
    const { goToCondition, deviceData, panelYear } = this.props
    let { tabTags, sensorType } = this.state
    return (
      <div className={styles['main']}>
        <header className={styles['data-overview-header']}>
          <div className={styles['data-overview-title']}>
            <i className='fa fa-bar-chart' aria-hidden='true' />
            <span>数据一览</span>
          </div>
          <div className={styles['data-overview-tabs']}>
            {
              tabTags.length > 0
              ? <Tabs onChange={this.changeTab} defaultActiveKey={sensorType}>
                {
                  tabTags.map((item, index) => {
                    return <TabPane tab={item.sensorType} key={item.sensorType}>
                      <ChannelData {...{
                        deviceData,
                        goToCondition,
                        filterData: this.props.filterData,
                        channelData: item.channelIds,
                        sensorType: sensorType,
                        panelYear
                      }} />
                    </TabPane>
                  })
                }
              </Tabs>
              : false
            }
          </div>
        </header>
      </div>
    )
  }
}

export default ChannelBoard
